/*
 * @Description: 关闭窗口
 */
import { useBaseInfoStore } from '@/store/modules/base-info.js';
import globalData from '@/plugins/data';
import api from "@/api";
import {fireEvent} from "@/handles/common/sdk";

/**
 * 刷新父页面opener方法
 * @param callback
 * @param releaseLock
 */
export default async function close(callback = () => window.close(), releaseLock = false) {
  if (globalData.isSummary){
    await fireEvent('summary-leavePage',{})
  }else {
    await fireEvent('newColl-leavePage',{})
  }
  window.isFormSubmit = false;
  if (globalData.openFrom === 'ucpc' || globalData.from === 'a8genius') {
    if (window.top.dealSuccess) {
      window.top.dealSuccess();
    } else {
      //致信打开的
      window.top.location.href = `${_ctxPath}/collaboration/collaboration.do?method=showDealSuccessfully`;
    }
    return;
  }
  //多页签模式
  var topWindow = window.getCtpTop();
  if (topWindow.isMultipleTabs) {
    let currentId = topWindow?.layoutTabsManager?.currentId;
    topWindow.refreshAllTabSection();
    let attribute = frameElement.getAttribute("id");
    if (attribute) {
      currentId = attribute.replace(/MenuIframe/g, "")
    }
    topWindow.closeCurrentTabIframe(true, currentId);
    return;
  }
  //弹窗模式
  const sectionIdList = [
    'pendingSection',
    'sentSection',
    'waitSendSection',
    'agentSection',
    'trackSection',
    'largeFontPendingSection',
    'projectCollaboration',
  ];
  try {
    const reload = window.getCtpTop()?.opener?.vPortal?.sectionHandler?.reload;
    if (reload) {
      //关闭前要调这个方法触发父窗口数据刷新
      sectionIdList.forEach(reload);
    } else {
      window?.opener?.loadPendingGrid && window.top.opener.loadPendingGrid();
    }
  } finally {
    try {
      //事件机制刷新列表
      window.refreshOpener();
    } finally {
      callback.call(this);
      window.location.href = "about:blank";
      window.opener = null;
      window.open("", "_self");
      window.close();
      window.location.href = `${_ctxPath}/collaboration/collaboration.do?method=showDealSuccessfully`
    }
  }
}

/**
 * 页面离开请求事件
 * 执行条件：用户自己关闭了浏览器的场景
 */
function pageLeaveAction() {
  const {affair, summary} = useBaseInfoStore().baseInfo?.businessData || {};
  const {
    id: summaryId,
    bodyType,
    processId,
    formAppid:formAppId,
    orgAccountId:accountId,
  } = summary||{};
  //协同更新查看时间的参数
  const {
    id: affairId,
    formRecordid:fromRecordId,
    firstViewDate:firstViewTime,
    signleViewPeriod,
  } = affair||{};
  //准备解锁的参数
  let releaseLock = {
    summaryId,
    bodyType,
    processId,
    fromRecordId,
    formAppId
  };
  //更新查看时间的参数
  let recordView = {
    affairId,
    firstViewTime,
    signleViewPeriod,
    accountId,
  }
  //目前只能用同步的方法，门户过来是同步执行的
  window.callBackendMethod("colManager", "onDealPageLeave", {DelLock: releaseLock, ViewRecord: recordView});
  // new Promise(()=>{
  //   return  api.commonPageLeave({releaseLock,recordView})
  // }).then(res=>console.log('协同页面手动关闭',res))
}

/**
 * 调用refreshAllTabSection执行刷新opener方法,此方法在多页签模式下会从门户里面回调
 * 提前等操作执行完毕后触发
 * @returns {boolean}
 */
window.refreshOpener = function () {
  //新增event触发刷新事件
  const {method = ''} = globalData;
  //新建的事项需要发新建事件
  if (method.includes("newColl")){
    localStorage.setItem('sendEvent', window.location.href);
    return true;
  }
  localStorage.setItem('pendingDoneEvent', window.location.href);
  if (window?.opener?.closeAndFresh){
    window.opener.closeAndFresh();
  }
  return true;
};

/**
 * 关闭页面强制刷新打开的页面,此方法在多页签模式下会从门户里面回调
 * 由用户主动点击关闭触发
 * @param openerId
 */
window.closePageRefreshOpener = function (openerId) {
  const { openFrom = '' } = globalData;
  //从待办打开的事项
  if (!openFrom.toLowerCase().includes("pending")){
    return;
  }
  //适配知会免提交
  const businessData = useBaseInfoStore().baseInfo.businessData;
  //是知会节点
  let permissionName = businessData?.nodePolicy?.permissionName;
  const {
    affair: {
      state,
      subState
    }
  } = businessData;
  //待办状态
  if (state === 3 || subState === 16) {
    pageLeaveAction();
    if (permissionName !== "inform") {
      return
    }
    //防止循环
    window.closePageRefreshOpener=()=>{}
    //知会免提交刷新opener页面
    close();
  }
};

/**
 * 注册页面关闭时候的监听，用户刷新opener页面
 */
window.addEventListener("beforeunload",  ()=> {
  //用户关闭浏览器非多页模式签模式
  var topWindow = window.getCtpTop();
  if (!topWindow.isMultipleTabs) {
    window.closePageRefreshOpener();
  }

})
